import { useEffect, useRef } from 'react'
import { Delete, FolderCode, FolderPlus } from '@icon-park/react'
import { NavLink, Outlet, useFetcher, useLoaderData, useSubmit } from 'react-router-dom'
import classNames from 'classnames'
import { useSnippetsStore } from '@renderer/stores'
import { Input } from 'antd'
import { useCategory } from '@renderer/hooks'
import styles from './style.module.less'
import { QuickNav } from './QuickNav'
import type { InputRef } from 'antd'

export function Category () {
  const inputRef = useRef<InputRef | null>(null)
  const snippetStore = useSnippetsStore()
  const categories = useLoaderData() as ICategory[]
  const { getDragHandlers } = useCategory(styles)
  const submit = useSubmit()
  const fetcher = useFetcher()

  const handleEditCategory = (cid: number) => {
    snippetStore.setEditCateId(cid)
  }

  useEffect(() => {
    if (!snippetStore.editCateId || !inputRef.current) return

    const { input } = inputRef.current
    if (!input) return

    const { value } = input
    if (!value) return

    input.setSelectionRange(0, value.length)
  }, [snippetStore.editCateId])

  return (
    <main className={styles.container}>
      {/* 文本片段侧边分类栏 */}
      <div className={styles.categories}>
        <div className='px-2 py-1 cursor-pointer font-[10px] text-t-secondary mt-2 flex items-center justify-between'>
          <span>快捷操作</span>
          <FolderPlus
            theme="outline"
            size="16"
            className='text-t-primary'
            onClick={() => {
              submit(null, { method: 'POST' })
            }}
          />
        </div>
        <QuickNav />
        <main className='mt-1'>
          {categories.map(cate => {
            if (snippetStore.editCateId === cate.id) {
              return (
                <div className={styles.cateEditContainer} key={cate.id}>
                  <Input
                    defaultValue={cate.name}
                    autoFocus
                    onPressEnter={(e) => {
                      const { value } = e.target as HTMLInputElement
                      fetcher.submit({ id: cate.id, name: value }, { method: 'PATCH' })
                      snippetStore.setEditCateId(null)
                    }}
                    onBlur={() => {
                      snippetStore.setEditCateId(null)
                    }}
                    ref={inputRef}
                  />
                </div>
              )
            }

            return (
              <NavLink
                to={`/manager/category/contents/${cate.id}`}
                className={({ isActive }) => {
                  return classNames({
                    [styles.active]: isActive,
                  })
                }}
                key={cate.id}
                onDoubleClick={(e) => {
                  e.stopPropagation()
                  e.preventDefault()
                  handleEditCategory(cate.id)
                }}
                {...getDragHandlers(cate.id)}
              >
                <span
                  className={styles.cateName}
                >
                  <FolderCode theme="outline" size="12" />
                  <span className='truncate flex-1'>{cate.name}</span>
                </span>
                <span className={styles.iconWrapper}>
                  <Delete
                    theme="outline"
                    size="14"
                    fill="currentColor"
                    className={styles.delete_icon}
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      submit({ id: cate.id }, { method: 'DELETE' })
                    }}
                  />
                </span>
              </NavLink>
            )
          })}
        </main>
      </div>
      <div className={styles.content}>
        <Outlet />
      </div>
    </main>
  )
}
